package task.manager.view;

import java.util.*;

import task.manager.model.Task;
import task.manager.model.TaskApplication;
import task.manager.view.EnhancedListAdapter;

import task.manager.R;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.*;

// TODO: Auto-generated Javadoc
/**
 * The Class TaskListView.
 */
public class TaskListView extends Activity {

	/** The tasks. */
	private LinkedList<Task> tasks;
	
	/** The filtered. */
	private LinkedList<Task> filtered;
	
	/** The tasknames. */
	private ArrayList<String> tasknames = new ArrayList<String>();
	
	/** The dates. */
	private ArrayList<String> dates = new ArrayList<String>();
	
	/** The array category. */
	private String[] arrayCategory = { "All", "Personal", "School", "Work" };
	
	/** The array completed. */
	private String[] arrayCompleted = { "In Progress", "All", "Completed" };
	
	/** The listview. */
	private ListView listview;
	
	/** The maps. */
	private Button newTask, clearDate, maps;
	
	/** The filter date. */
	private EditText filterDate;
	
	/** The completed. */
	private Spinner category, completed;
	
	/** The sort date. */
	private Date sortDate;
	
	/** The new day. */
	private int newYear, newMonth, newDay;
	
	/** The facade. */
	final TaskApplication facade = TaskApplication.getInstance();

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		setTitle("Task List");
		clearDate = (Button) findViewById(R.id.clearDate);
		filterDate = (EditText) findViewById(R.id.afterDate);
		newTask = (Button) findViewById(R.id.bNewTask);
		listview = (ListView) findViewById(R.id.listView1);
		tasks = facade.getTaskList();
		maps = (Button) findViewById(R.id.bMap);

		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(
				TaskListView.this, android.R.layout.simple_spinner_item,
				arrayCategory);
		category = (Spinner) findViewById(R.id.sCategory);
		category.setAdapter(categoryAdapter);

		ArrayAdapter<String> completedAdapter = new ArrayAdapter<String>(
				TaskListView.this, android.R.layout.simple_spinner_item,
				arrayCompleted);
		completed = (Spinner) findViewById(R.id.sCompleted);
		completed.setAdapter(completedAdapter);

		sortDate = null;
		filtered = facade.filter(category.getSelectedItem().toString(),
				completed.getSelectedItem().toString(), sortDate);
		Iterator<Task> it = filtered.iterator();
		while (it.hasNext()) {
			Task curr = it.next();
			tasknames.add(curr.getTaskName());
			dates.add((curr.getDate().getMonth() + 1) + "/"
					+ curr.getDate().getDate() + "/" + curr.getDate().getYear());
		}

		listview.setAdapter(new EnhancedListAdapter(this, tasknames, dates,
				filtered));
		listview.setClickable(true);

		category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				tasknames.clear();
				dates.clear();
				filtered = facade.filter(category.getSelectedItem().toString(),
						completed.getSelectedItem().toString(), sortDate);
				Iterator<Task> it = filtered.iterator();
				while (it.hasNext()) {
					Task curr = it.next();
					tasknames.add(curr.getTaskName());
					dates.add((curr.getDate().getMonth() + 1) + "/"
							+ curr.getDate().getDate() + "/"
							+ curr.getDate().getYear());
				}

				listview.setAdapter(new EnhancedListAdapter(TaskListView.this,
						tasknames, dates, filtered));
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		completed.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						tasknames.clear();
						dates.clear();
						filtered = facade.filter(category.getSelectedItem()
								.toString(), completed.getSelectedItem()
								.toString(), sortDate);
						Iterator<Task> it = filtered.iterator();
						while (it.hasNext()) {
							Task curr = it.next();
							tasknames.add(curr.getTaskName());
							dates.add((curr.getDate().getMonth() + 1) + "/"
									+ curr.getDate().getDate() + "/"
									+ curr.getDate().getYear());
						}

						listview.setAdapter(new EnhancedListAdapter(TaskListView.this,
								tasknames, dates, filtered));
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		newTask.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(TaskListView.this, AddNewTask.class);
				startActivityForResult(intent, 0);
			}
		});
		
		maps.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent myIntent = new Intent(v.getContext(), AndroidGoogleMapsProjectActivity.class);
				TaskListView.this.startActivity(myIntent);
			}
		});

		clearDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				filterDate.setText("");

				tasknames.clear();
				dates.clear();
				sortDate = null;
				filtered = facade.filter(category.getSelectedItem().toString(),
						completed.getSelectedItem().toString(), sortDate);
				Iterator<Task> it = filtered.iterator();
				while (it.hasNext()) {
					Task curr = it.next();
					tasknames.add(curr.getTaskName());
					dates.add((curr.getDate().getMonth() + 1) + "/"
							+ curr.getDate().getDate() + "/"
							+ curr.getDate().getYear());
				}
				listview.setAdapter(new EnhancedListAdapter(TaskListView.this,
						tasknames, dates, filtered));
			}
		});

		filterDate.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					showDialog(0);
				}
				return false;
			}
		});

		filterDate.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					showDialog(0);
				} else {
					dismissDialog(0);
				}
			}
		});

		final Calendar c = Calendar.getInstance();
		newYear = c.get(Calendar.YEAR);
		newMonth = c.get(Calendar.MONTH);
		newDay = c.get(Calendar.DAY_OF_MONTH);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		super.onCreateDialog(id);
		DatePickerDialog dateDlg = new DatePickerDialog(this,
				new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						newYear = year;
						newMonth = monthOfYear;
						newDay = dayOfMonth;
						updateDate();

						tasknames.clear();
						dates.clear();
						filtered = facade.filter(category.getSelectedItem()
								.toString(), completed.getSelectedItem()
								.toString(), sortDate);
						Iterator<Task> it = filtered.iterator();
						while (it.hasNext()) {
							Task curr = it.next();
							tasknames.add(curr.getTaskName());
							dates.add((curr.getDate().getMonth() + 1) + "/"
									+ curr.getDate().getDate() + "/"
									+ curr.getDate().getYear());
						}
						listview.setAdapter(new EnhancedListAdapter(TaskListView.this,
								tasknames, dates, filtered));
					}
				}, newYear, newMonth, newDay);
		return dateDlg;
	}

	/**
	 * Update date.
	 */
	private void updateDate() {
		sortDate = new Date(newYear, newMonth, newDay);
		filterDate.setText(new StringBuilder().append(newMonth + 1).append("/")
				.append(newDay).append("/").append(newYear).append(" "));
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			TaskApplication facade = TaskApplication.getInstance();
			tasks = facade.getTaskList();
			tasknames.clear();
			dates.clear();
			Iterator<Task> it = tasks.iterator();
			while (it.hasNext()) {
				Task curr = it.next();
				tasknames.add(curr.getTaskName());

				dates.add((curr.getDate().getMonth() + 1) + "/"
						+ curr.getDate().getDate() + "/"
						+ curr.getDate().getYear());
			}

			filtered = facade.filter(category.getSelectedItem()
					.toString(), completed.getSelectedItem()
					.toString(), sortDate);
			listview.setAdapter(new EnhancedListAdapter(TaskListView.this,
					tasknames, dates, filtered));
		}
	}
}
